import json
import datetime

from django.shortcuts import render
from django.views import View
from django.http import HttpResponseForbidden, JsonResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from login.models import User

from .models import Corp, TourBooking, Trip


# Create your views here.

def get_client_list():
    # 获取所有用户
    clients = User.objects.filter(identity=User.VISITOR)
    # 封装数据
    client_list = []
    index = 1
    for client in clients:
        client_item = {
            'value': index,
            'title': client.username,
            'disabled': '',
            'checked': '',
        }
        index = index + 1
        client_list.append(client_item)

    return client_list


def get_current_corp(request):
    # 获取用户名
    username = request.session.get('username')
    # 获取用户对象
    user = User.objects.get(username=username)
    # 获取当前公司对象
    corp = Corp.objects.get(owner=user)

    return corp


class IndexView(LoginRequiredMixin, View):
    """首页视图"""

    def get(self, request):
        nickname = request.session.get('nickname')
        if nickname:
            context = {
                'nickname': nickname,
            }
            return render(request, 'corp/index.html', context)
        else:
            return HttpResponseForbidden('登录状态有误')


class WelcomeView(View):
    """欢迎页面视图"""

    def get(self, request):
        nickname = request.session.get('nickname')
        if nickname:
            context = {
                'nickname': nickname,
            }
            return render(request, 'corp/welcome.html', context)
        else:
            return HttpResponseForbidden('登录状态有误')


class BookingInfoView(View):
    """订单信息视图"""

    def get(self, request):
        return render(request, 'corp/bookings.html')


class GetBookingInfoView(View):
    """获取订单信息视图"""

    def get(self, request):
        # 获取当前公司对象
        corp = get_current_corp(request)

        # 查询当前公司对应的订单
        bookings = TourBooking.objects.filter(corp=corp)

        # 封装数据
        booking_list = []
        for booking in bookings:
            booking_item = {
                'id': booking.id,
                'price': booking.price,
            }
            booking_list.append(booking_item)

        return JsonResponse({
            'code': 0,
            'msg': '',
            'data': booking_list,
        })


class BookingManageView(View):
    """订单管理视图"""

    def post(self, request):
        # 获取操作类型
        code = request.POST.get('code')
        # 获取当前公司对象
        corp = get_current_corp(request)

        if code == '100':  # 新增操作
            # 获取参数
            guests = request.POST.get('guests')
            price = request.POST.get('price')

            # print(guests)
            # print(type(guests))
            guests = json.loads(guests)
            # print(type(guests))

            # 处理参数
            price = float(price)

            # 新增订单
            booking = TourBooking.objects.create(price=price, corp=corp)
            # 添加顾客
            for guest_name in guests:
                guest = User.objects.get(username=guest_name)
                booking.guests.add(guest)

        elif code == '200':  # 删除操作
            # 获取参数
            booking_id = request.POST.get('id')
            booking_id = int(booking_id)

            # 获取对应booking
            booking = TourBooking.objects.get(id=booking_id)
            # 先删除tirps
            Trip.objects.filter(booking=booking).delete()
            # 再删除booking对象
            booking.delete()

        elif code == '300':  # 编辑操作
            # 获取参数
            guests = request.POST.get('guests')
            price = request.POST.get('price')
            booking_id = request.POST.get('booking_id')

            # 处理参数
            guests = json.loads(guests)
            price = float(price)
            booking_id = int(booking_id)

            # 获取对应booking
            booking = TourBooking.objects.get(id=booking_id)
            # 修改值
            booking.price = price
            booking.guests.clear()
            for guest_name in guests:
                guest = User.objects.get(username=guest_name)
                booking.guests.add(guest)
            booking.save()
        else:
            return HttpResponseForbidden('操作类型不合法')

        return JsonResponse({
            'status': 'OK',
        })


class AddBookingView(View):
    """新增订单表单视图"""

    def get(self, request):
        return render(request, 'corp/views/add_booking.html')

    def post(self, request):
        """用于获取全部顾客对象来渲染表单"""
        client_list = get_client_list()

        return JsonResponse({
            'status': 'OK',
            'client_list': client_list,
        })


class EditBookingView(View):
    """编辑订单表单视图"""

    def get(self, request):
        # 获取booking_id
        booking_id = request.GET.get('booking_id')
        booking_id = int(booking_id)

        booking = TourBooking.objects.get(id=booking_id)

        # 封装数据
        context = {
            'booking_id': booking_id,
            'price': booking.price,
        }

        return render(request, 'corp/views/edit_booking.html', context)

    def post(self, request):
        # 获取booking_id
        booking_id = request.POST.get('booking_id')
        booking_id = int(booking_id)

        booking = TourBooking.objects.get(id=booking_id)
        guests = booking.guests.all()
        client_list = []
        index = 1
        for guest in guests:
            guest_item = {
                'value': index,
                'title': guest.username,
                'disabled': '',
                'checked': 'true',
            }
            index = index + 1
            client_list.append(guest_item)

        clients = User.objects.filter(identity=User.VISITOR)
        for client in clients:
            if client in guests:
                continue
            else:
                client_item = {
                    'value': index,
                    'title': client.username,
                    'disabled': '',
                    'checked': '',
                }
                index = index + 1
                client_list.append(client_item)

        return JsonResponse({
            'status': 'OK',
            'client_list': client_list,
        })


class BookingDetailView(View):
    """订单详细信息(行程信息)视图"""

    def get(self, request):
        booking_id = request.GET.get('booking_id')
        context = {
            'booking_id': booking_id,
        }

        return render(request, 'corp/views/booking_detail.html', context)

    def post(self, request):
        # 获取参数
        booking_id = request.POST.get('booking_id')
        booking_id = int(booking_id)
        # 获取对应booking
        booking = TourBooking.objects.get(id=booking_id)

        # 获取该booking的行程
        trips = Trip.objects.filter(booking=booking)

        # 封装数据
        trip_list = []
        fmt = '%Y-%m-%d'
        for trip in trips:
            trip_item = {
                'id': trip.id,
                'date_start': trip.date_start.strftime(fmt),
                'date_end': trip.date_end.strftime(fmt),
                'attraction': trip.attraction,
            }
            trip_list.append(trip_item)

        return JsonResponse({
            'data': trip_list,
        })


def date_str_process(date_str, fmt):
    date = datetime.datetime.strptime(date_str, fmt)
    date = date.date()

    return date


class AddTourView(View):
    """增加行程视图"""

    def get(self, request):
        booking_id = request.GET.get('booking_id')

        context = {
            'booking_id': booking_id,
        }

        return render(request, 'corp/views/add_tour.html', context)

    def post(self, request):
        # 获取参数
        booking_id = request.POST.get('booking_id')
        date_start = request.POST.get('date_start')
        date_end = request.POST.get('date_end')
        attraction = request.POST.get('attraction')

        # 参数处理
        fmt = '%Y-%m-%d'
        date_start = date_str_process(date_start, fmt)
        date_end = date_str_process(date_end, fmt)
        booking_id = int(booking_id)

        # 获取对应booking
        booking = TourBooking.objects.get(id=booking_id)
        # 新增行程
        trip = Trip.objects.create(booking=booking, date_start=date_start,
                                   date_end=date_end, attraction=attraction)

        return JsonResponse({
            'status': 'OK',
        })


class GuestsDetailView(View):
    """顾客信息视图"""

    def get(self, request):
        booking_id = request.GET.get('booking_id')
        context = {
            'booking_id': booking_id,
        }
        return render(request, 'corp/views/guests_detail.html', context)

    def post(self, request):
        # 获取参数
        booking_id = request.POST.get('booking_id')
        booking_id = int(booking_id)

        booking = TourBooking.objects.get(id=booking_id)
        guests = booking.guests.all()
        guest_list = []
        for guest in guests:
            guest_item = {
                'id': guest.id,
                'username': guest.username,
                'nickname': guest.nickname,
            }
            guest_list.append(guest_item)

        return JsonResponse({
            'data': guest_list,
        })
